<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1080">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      :disabled="disabled"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="盘点单号" prop="no">
            <el-input disabled v-model="formData.no" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="盘点时间" prop="createTime">
            <el-date-picker
              v-model="formData.createTime"
              disabled
              type="datetime"
              value-format="x"
              placeholder="选择盘点时间"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="部门等级" prop="warehouseLevel">
            <el-input disabled v-model="formData.warehouseLevel" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="部门名称" prop="deptId">
            <el-input disabled v-model="formData.deptName" />
          </el-form-item>
        </el-col>
         <el-col :span="16">
          <el-form-item label="审批意见" prop="remark" v-if="formData.status ==2 || formData.status == 3">
            <el-input
              type="textarea"
              v-model="formData.remark"
              :rows="1"
              disabled
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="附件" prop="fileUrl">
            <UploadFile :is-show-tip="false" disabled v-model="formData.fileUrl" :limit="1" />
          </el-form-item>
        </el-col> -->
      </el-row>
    </el-form>
    <!-- 子表的表单 -->
    <ContentWrap>
      <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
        <el-tab-pane label="盘点产品清单" name="item">
          <StockCheckItemForm ref="itemFormRef" :items="formData.items" :disabled="disabled" />
        </el-tab-pane>
      </el-tabs>
    </ContentWrap>
    <template #footer>
      <el-button
        @click="openApproveDialog(true)"
        v-hasPermi="['erp:stock-check:update-status']"
        type="success"
        :disabled="formLoading"
        v-if="formType === 'updateStatus'"
      >
        审批通过
      </el-button>
      <el-button
        @click="openApproveDialog(false)"
        v-hasPermi="['erp:stock-check:update-status']"
        type="danger"
        :disabled="formLoading"
        v-if="formType === 'updateStatus'"
      >
        拒绝
      </el-button>
      <el-button
        @click="handleExport()"
        :loading="exportLoading"
        v-hasPermi="['erp:stock-check:export']"
        type="primary"
        v-if="formType === 'detail'"
      >
        导出
      </el-button>
    </template>
    

    <!-- 审批意见二层弹窗 -->
    <Dialog
      :title="approveDialogTitle"
      v-model="approveDialogVisible"
      width="400"
    >
      <el-form
        ref="approveFormRef"
        :model="approveFormData"
        :rules="approveFormRules"
        label-width="100px"
      >
        <el-form-item label="审批意见" prop="reason">
          <el-input
            v-model="approveFormData.reason"
            placeholder="请输入审批意见"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleAudit(approvePassStatus)" type="primary">确定</el-button>
        <el-button @click="approveDialogVisible = false">取消</el-button>
      </template>
    </Dialog>
  </Dialog>
</template>

<script setup lang="ts">
import { StockCheckApi, StockCheckVO } from '@/api/spd/hospitaloffice/stockcheck'
import StockCheckItemForm from './components/StockCheckItemForm1.vue'
import { DeptVO } from '@/api/system/dept'
import * as DeptApi from '@/api/system/dept'
import * as TaskApi from '@/api/bpm/task' // 引入第一条消息中的任务API
import { ref, reactive } from 'vue'

/** ERP 其它盘点单表单 */
defineOptions({ name: 'StockCheckForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 主弹窗的是否展示
const dialogTitle = ref('') // 主弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改；detail - 详情
const formData = ref({
  id: undefined,
  deptName: undefined,
  customerId: undefined,
  createTime: undefined,
  remark: undefined,
  deptId: undefined,
  fileUrl: '',
  processInstanceId: undefined,
  warhouseLevel: undefined,
  items: [],
})
const task = ref('') // 流程实例ID
const formRules = reactive({
  // createTime: [{ required: true, message: '盘点时间不能为空', trigger: 'blur' }]
})
const disabled = computed(() => formType.value === 'detail')
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('item')
const itemFormRef = ref()
// const props = defineProps<{
//   taskId: string // 流程任务ID
// }>()

// 审批意见弹窗相关数据
const approveDialogVisible = ref(false) // 审批意见弹窗是否展示
const approveDialogTitle = ref('') // 审批意见弹窗标题
const approveFormData = ref({
  reason: ''
})
const approveFormRules = reactive({
  reason: [{ required: true, message: '审批意见不能为空', trigger: 'blur' }]
})
const approveFormRef = ref()
const approvePassStatus = ref<boolean>() // 记录审批状态

/** 打开弹窗 */
const open = async (type: string, id?: number, taskId?: string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  task.value = taskId ?? '';
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await StockCheckApi.getStockCheck(id)
      const sysDept = await DeptApi.getDept(Number(formData.value.deptId))
      formData.value.deptName = sysDept.name
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  await itemFormRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as StockCheckVO
    if (formType.value === 'create') {
      await StockCheckApi.createStockCheck(data)
      message.success(t('common.createSuccess'))
    } else {
      await StockCheckApi.updateStockCheck(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 打开审批意见弹窗 */
const openApproveDialog = (pass: boolean) => {
  approveDialogVisible.value = true
  approveDialogTitle.value = pass ? '审批通过 - 输入审批意见' : '拒绝 - 输入审批意见'
  approvePassStatus.value = pass
  approveFormData.value.reason = '' // 清空审批意见
}

const handleExport = async () => {
}

/** 处理审批通过和不通过的操作 */
const handleAudit = async (pass: boolean) => {
  formLoading.value = true
  try {
    // 校验审批意见表单
    const approveElForm = approveFormRef.value
    if (!approveElForm) return
    const valid = await approveElForm.validate()
    if (!valid) return

    // 2.1 提交审批
    if (pass) {
      await StockCheckApi.approveStockCheck(task.value,approveFormData.value.reason, formData.value.id)
      // await TaskApi.approveTask(data)
      message.success('审批通过成功')
    } else {
      await StockCheckApi.rejectStockCheck(task.value,approveFormData.value.reason, formData.value.id)
      // await TaskApi.rejectTask(data)
      message.success('审批不通过成功')
    }
    approveDialogVisible.value = false
    dialogVisible.value = false
    // 2.2 加载最新数据
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deptName: undefined,
    customerId: undefined,
    createTime: undefined,
    remark: undefined,
    deptId: undefined,
    fileUrl: undefined,
    processInstanceId: undefined,
    warhouseLevel: undefined,
    items: [],
  }
  formRef.value?.resetFields()
}

</script>